// these first variables used to be in the configureMe.js file.  They were moved to make things easier...
//
var enableWallpaper = true;   //true|false
var iconExtWall = ".png";     //'.png'|.'gif' etc.
var enableLockScreen = false; //true|false [Currently, it is suggested that the lockScreen is disabled.]
var stylesheetLock = 'iWeather3'; //See above.
var iconSetLock = 'iWeather'; //See above.
var iconExtLock = '.png';     //See above.

// The other available source is 'yahooWeather' which for the 'locale'
// requires a US zip or location code (e.g. UKXX0085 or CHXX0008) from http://weather.yahoo.com
var source = 'appleAccuweatherStolen' //'appleAccuweatherStolen'|'yahooWeather'
//var source = 'yahooWeather' // yahooWeather doesn't return values for the forcast for the coming days, so it isn't as good IMO
//

var postal;
var demoMode =false;
var enabled;

var xmlReq = new XMLHttpRequest();
var launchReq = new XMLHttpRequest();

if (location.href.indexOf("Wallpaper")  == -1){
	stylesheet = stylesheetLock;
	iconSet = iconSetLock;
	iconExt = iconExtLock;
	enabled = enableLockScreen;
}else{
	stylesheet = stylesheetWall;
	iconSet = iconSetWall;
	iconExt = iconExtWall;
	enabled = enableWallpaper;
}

if(enabled == true){
if(iconSet == null || iconSet == 'null' || iconSet == ""){
	var iconSet = stylesheet;
}

var headID = document.getElementsByTagName("head")[0];         
var styleNode = document.createElement('link');
styleNode.type = 'text/css';
styleNode.rel = 'stylesheet';
styleNode.href = 'Stylesheets/'+stylesheet+'.css';
headID.appendChild(styleNode);

var scriptNode = document.createElement('script');
scriptNode.type = 'text/javascript';
scriptNode.src = 'Sources/'+source+'.js';
headID.appendChild(scriptNode);
}

function onLoad(){
	
	update();
	
	if (enabled == true){ 
	if (demoMode == true){
		document.getElementById("weatherIcon").src="Icon Sets/"+iconSet+"/"+"cloudy1"+iconExt;
		document.getElementById("city").innerText="Somewhere";
		document.getElementById("desc").innerText="Partly Cloudy";
		document.getElementById("temp").innerText="100º";		
		document.getElementById("forecast").innerText="Sun";	
	}else{ 
	document.getElementById("weatherIcon").src="Icon Sets/"+iconSet+"/"+"dunno"+iconExt;
	validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)
	}
	}else{
		document.getElementsByTagName("body")[0].innerText='';
	}
}

function convertTemp(num)
{
	if (isCelsius == true)
		return Math.round ((num - 32) * 5 / 9);
	else
		return num;
}

function setPostal(obj){
	
	if (obj.error == false){
		if(obj.cities.length > 0){
			postal = escape(obj.cities[0].zip).replace(/^%u/g, "%")
			document.getElementById("WeatherContainer").className = "";	
			weatherRefresherTemp();
		}else{
			document.getElementById("city").innerText="Not Found";
			document.getElementById("WeatherContainer").className = "errorLocaleNotFound";	
		}
	}else{
		document.getElementById("city").innerText=obj.errorString;
		document.getElementById("WeatherContainer").className = "errorLocaleValidate";	
		setTimeout('validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)', Math.round(1000*60*5));
	}
}

function dealWithWeather(obj){

	if (obj.error == false){
		document.getElementById("city").innerText=obj.city;
		document.getElementById("desc").innerText=obj.description.toLowerCase();
		translatedesc=obj.description.toLowerCase();

      // ************************************Traduction Française***********************************
      
      // *******    Description traduction  ***************************
   if (translatedesc=='description') { document.getElementById("desc").innerHTML='Your Description';   }
      if (translatedesc=='tornado') { document.getElementById("desc").innerHTML='Tornade';    }
      if (translatedesc=='tropical storm') { document.getElementById("desc").innerHTML='Orage tropical';    }
      if (translatedesc=='hurricane') { document.getElementById("desc").innerHTML='Ouragan';     }
      if (translatedesc=='severe thunderstorms') { document.getElementById("desc").innerHTML='Orage violent';   }
      if (translatedesc=='thunderstorms') { document.getElementById("desc").innerHTML='Orage';    }
      if (translatedesc=='mixed rain and snow') { document.getElementById("desc").innerHTML='Pluie et neige';    }
      if (translatedesc=='mixed rain and sleet') { document.getElementById("desc").innerHTML='Pluie et verglas';   }
      if (translatedesc=='mixed snow and sleet') { document.getElementById("desc").innerHTML='Neige et verglas';    }
      if (translatedesc=='freezing drizzle') { document.getElementById("desc").innerHTML='Brouillard givrant!';   }
      if (translatedesc=='drizzle') { document.getElementById("desc").innerHTML='Brouillard';    }
      if (translatedesc=='freezing rain') { document.getElementById("desc").innerHTML='Pluie verglacante';    }
      if (translatedesc=='showers') { document.getElementById("desc").innerHTML='Averses';    }
      if (translatedesc=='snow flurries') { document.getElementById("desc").innerHTML='Bourrasques de neige';    }
      if (translatedesc=='light snow showers') { document.getElementById("desc").innerHTML='Petites chutes de neige';    }
      if (translatedesc=='blowing snow') { document.getElementById("desc").innerHTML='Vent et neige';    }
      if (translatedesc=='snow') { document.getElementById("desc").innerHTML='Neige';    }
      if (translatedesc=='hail') { document.getElementById("desc").innerHTML='Grele';    }
      if (translatedesc=='sleet') { document.getElementById("desc").innerHTML='Verglas';    }
      if (translatedesc=='dust') { document.getElementById("desc").innerHTML='Brume';    }
      if (translatedesc=='foggy') { document.getElementById("desc").innerHTML='Brume';    }      
      if (translatedesc=='haze') { document.getElementById("desc").innerHTML='Brume';    }
      if (translatedesc=='smoky') { document.getElementById("desc").innerHTML='Brume';    }
      if (translatedesc=='blustery') { document.getElementById("desc").innerHTML='Vent';    }
      if (translatedesc=='windy') { document.getElementById("desc").innerHTML='Vent';    }
      if (translatedesc=='cold') { document.getElementById("desc").innerHTML='Froid';     }
      if (translatedesc=='cloudy') { document.getElementById("desc").innerHTML='Nuageux';    }
      if (translatedesc=='mostly cloudy') { document.getElementById("desc").innerHTML='Passage nuageux';    }
      if (translatedesc=='partly cloudy') { document.getElementById("desc").innerHTML='Passage nuageux';    }
      if (translatedesc=='clear') { document.getElementById("desc").innerHTML='Ciel clair';    }
      if (translatedesc=='sunny') { document.getElementById("desc").innerHTML='Ensoleille';    }
      if (translatedesc=='fair') { document.getElementById("desc").innerHTML='Beau temps';    }
      if (translatedesc=='mixed rain and hail') { document.getElementById("desc").innerHTML='Pluie et grele';   }
      if (translatedesc=='hot') { document.getElementById("desc").innerHTML='Tres chaud';    }
      if (translatedesc=='isolated thunderstorms') { document.getElementById("desc").innerHTML='Passages nuageux avec orages';    }
      if (translatedesc=='scattered thunderstorms') { document.getElementById("desc").innerHTML='Orage et eclaircies';    }
      if (translatedesc=='scattered showers') { document.getElementById("desc").innerHTML='Pluies et eclaircies';   }
      if (translatedesc=='heavy snow') { document.getElementById("desc").innerHTML='Chute de neige importante';    }
      if (translatedesc=='scattered snow showers') { document.getElementById("desc").innerHTML='Petites chutes de neige';    }
      if (translatedesc=='partly cloudy') { document.getElementById("desc").innerHTML='Partiellement couvert';    }
      if (translatedesc=='thundershowers') { document.getElementById("desc").innerHTML='Tonnerre';    }
      if (translatedesc=='snow showers') { document.getElementById("desc").innerHTML='Chutes de neige';    }
      if (translatedesc=='isolated thundershowers') { document.getElementById("desc").innerHTML='Tonnerre et eclaircies';    }
      if (translatedesc=='light rain shower') { document.getElementById("desc").innerHTML='Pluie fine';     }
      if (translatedesc=='not available') { document.getElementById("desc").innerHTML='Aucune info';    }
      if (translatedesc=='showers in the vicinity') { document.getElementById("desc").innerHTML='Pluie voisine';    }
      if (translatedesc=='partly sunny') { document.getElementById("desc").innerHTML='Partiellement ensoleille';     }
      if (translatedesc=='ground fog') { document.getElementById("desc").innerHTML='Brouillard';     }
      if (translatedesc=='light drizzle') { document.getElementById("desc").innerHTML='Legere bruine';     }
      if (translatedesc=='light rain') { document.getElementById("desc").innerHTML='Legere pluie';    }


            

      // *******  Fin Traduction  ***************************

		
		if(useRealFeel == true){
			tempValue = convertTemp(obj.realFeel);
		}else{
			tempValue = convertTemp(obj.temp)
		}
		document.getElementById("temp").innerText=tempValue+"Âº";
		document.getElementById("weatherIcon").src="Icon Sets/"+iconSet+"/"+MiniIcons[obj.icon]+iconExt;
		
		/*ProductRed*/
		lastResults = new Array;
		lastResults[0] = {daycode:obj.daycode, icon:obj.icon, hi:obj.hi, lo:obj.lo, now:obj.temp};
		var c = obj.forecast.length;
		if (c > 6) c = 6; // just to be safe
		var i = 0;
		while (i < c)
		{
			var forecast = obj.forecast[i];

			document.getElementById('day'+i).innerText = jour[forecast.daycode];
			document.getElementById('hi'+i).innerText = convertTemp(forecast.hi)+"Âº";;
			document.getElementById('low'+i).innerText = convertTemp(forecast.lo)+"Âº";;

			document.getElementById('wIcon'+i).src="Icon Sets/"+iconSet+"/"+MiniIcons[forecast.icon]+iconExt;
			
			lastResults[i+1] = {daycode:forecast.daycode, icon:forecast.icon, hi:forecast.hi, lo:forecast.lo};

			i = i + 1;
		}
		/*ProductRed*/

		document.getElementById("WeatherContainer").className = "";	

		
	}else{
		//Could be down to any number of things, which is unhelpful...
		document.getElementById("WeatherContainer").className = "errorWeatherDataFetch";	
	}
	
	
}

function weatherRefresherTemp(){ //I'm a bastard ugly hack. Hate me.
	fetchWeatherData(dealWithWeather,postal);
	setTimeout(weatherRefresherTemp, 60*1000*updateInterval);
}

function showElement(name)
{
    document.getElementById(name + "Icon").style.display = 'inline';

    if (xmlReq.responseXML.getElementsByTagName("MMS")[0].firstChild.nodeValue == "1") {
    document.getElementById("MMSNumber").innerHTML = "<img src='imgs/mms.png' />1 New Multimedia Message";
    } else {            
    document.getElementById("MMSNumber").innerHTML = "<img src='imgs/mms.png' />" + xmlReq.responseXML.getElementsByTagName("MMS")[0].firstChild.nodeValue + " New Multimedia Messages";
    }
    
    if (xmlReq.responseXML.getElementsByTagName("SMS")[0].firstChild.nodeValue == "1") {
    document.getElementById("SMSNumber").innerHTML = "<img src='imgs/sms.png' />1 New Text Message";
    } else {            
    document.getElementById("SMSNumber").innerHTML = "<img src='imgs/sms.png' />" + xmlReq.responseXML.getElementsByTagName("SMS")[0].firstChild.nodeValue + " New Text Messages";
    }
    
    if (xmlReq.responseXML.getElementsByTagName("Call")[0].firstChild.nodeValue == "1") {
    document.getElementById("CallNumber").innerHTML = "<img src='imgs/call.png' />1 Missed Call/Voicemail";
    } else {            
    document.getElementById("CallNumber").innerHTML = "<img src='imgs/call.png' />" + xmlReq.responseXML.getElementsByTagName("Call")[0].firstChild.nodeValue + " Missed Calls/Voicemails";
    }
    
    if (xmlReq.responseXML.getElementsByTagName("Mail")[0].firstChild.nodeValue == "1") {
    document.getElementById("MailNumber").innerHTML = "<img src='imgs/mail.png' />1 New E-Mail";
    } else {            
    document.getElementById("MailNumber").innerHTML = "<img src='imgs/mail.png' />" + xmlReq.responseXML.getElementsByTagName("Mail")[0].firstChild.nodeValue + " New E-Mails";
    }

	if (xmlReq.responseXML.getElementsByTagName("IM")[0].firstChild.nodeValue == "1") {
    document.getElementById("IMNumber").innerHTML = "<img src='imgs/im.png' />1 New Instant Message";
    } else {            
    document.getElementById("IMNumber").innerHTML = "<img src='imgs/im.png' />" + xmlReq.responseXML.getElementsByTagName("IM")[0].firstChild.nodeValue + " New Instant Messages";
    }
}

function hideElement(name)
{
    document.getElementById(name + "Icon").style.display = 'none'; 
}

function updateIcon(name) 
{
var show = 0;
    try
    {
    if (xmlReq.responseXML.getElementsByTagName(name)[0].firstChild.nodeValue != "0")
	    show = 1;
    }
    catch(error)
    {
}

if (show)
	showElement(name);
    else
        hideElement(name);
}

function processXml() 
{
    if (xmlReq.readyState != 4) 
        return;

    if (xmlReq.status != 200 && xmlReq.status != 0) 
        return;

    updateIcon("Calendar");
    updateIcon("Call");
    updateIcon("RSS");	    
    updateIcon("MMS");	    
    updateIcon("SMS");	    
    updateIcon("IM");	    
    updateIcon("Mail");
	updateIcon("Silent");
}

function update()
{

    xmlReq.onreadystatechange = processXml;
xmlReq.timeout = 2000;
    xmlReq.open("GET", "http://127.0.0.1:16322/status", true);
    xmlReq.send();

    setTimeout(update, 3000);
}

function iconClick(name)
{
}
